package com.meals.system.api.user;

import com.meals.system.api.user.param.SaveOrderParam;
import com.meals.system.api.user.vo.WhitesMealOrderDetailVO;
import com.meals.system.api.user.vo.WhitesMealOrderItemVO;
import com.meals.system.api.user.vo.WhitesMealOrderListVO;
import com.meals.system.api.user.vo.WhitesMealShoppingCartItemVO;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.config.annotation.TokenToSystemUser;
import com.meals.system.entity.SystemUser;
import com.meals.system.entity.SystemUserAddress;
import com.meals.system.service.WhitesMealOrderService;
import com.meals.system.service.WhitesMealShoppingCartService;
import com.meals.system.service.WhitesMealUserAddressService;
import com.meals.system.util.PageQueryUtil;
import com.meals.system.util.PageResult;
import com.meals.system.util.Result;
import com.meals.system.util.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/10
 */
@RestController
@Api(value = "v1", tags = "3-2.白餐系统用户订单操作相关接口")
@RequestMapping("/user-api/v1")
public class WhitesMealUserOrderAPI {

    @Resource
    private WhitesMealShoppingCartService whitesMealShoppingCartService;
    @Resource
    private WhitesMealOrderService whitesMealOrderService;
    @Resource
    private WhitesMealUserAddressService whitesMealUserAddressService;


    @PostMapping("/saveOrder")
    @ApiOperation(value = "生成订单接口", notes = "传参为地址id和购物id数组")
    public Result<String> saveOrder(@ApiParam(value = "订单参数") @RequestBody SaveOrderParam saveOrderParam, @TokenToSystemUser SystemUser loginSystemUser){
        int priceTotal = 0;
        if (saveOrderParam == null || saveOrderParam.getAddressId() == null || saveOrderParam.getCartItemIds() == null || saveOrderParam.getCartItemIds().length < 1){
            SystemException.fail(ServiceResultEnum.PARAM_ERROR.getResult());
        }
        List<WhitesMealShoppingCartItemVO> itemsSave = whitesMealShoppingCartService.getCartItemsForSettle(Arrays.asList(saveOrderParam.getCartItemIds()), loginSystemUser.getUserId());
        if (CollectionUtils.isEmpty(itemsSave)){
            SystemException.fail(ServiceResultEnum.PARAM_ERROR.getResult());
        } else {
            // 总价判断 WhitesMEalOrderService saveOrder方法也有判断
            for (WhitesMealShoppingCartItemVO whitesMealShoppingCartItemVO : itemsSave){
                priceTotal += whitesMealShoppingCartItemVO.getGoodsCount() * whitesMealShoppingCartItemVO.getSellingPrice();
            }
            if (priceTotal <= 0){
                SystemException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
            }
            SystemUserAddress systemUserAddress = whitesMealUserAddressService.getSystemUserAddressById(saveOrderParam.getAddressId());
            // 登录用户id和操作数据用户id是否相等
            if (!loginSystemUser.getUserId().equals(systemUserAddress.getUserId())){
                return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
            }
            // 保存订单 返回订单号
            String saveOrderResult = whitesMealOrderService.saveOrder(loginSystemUser, systemUserAddress, itemsSave);
            Result result = ResultGenerator.genSuccessResult();
            result.setData(saveOrderResult);
            return result;
        }
        return ResultGenerator.genFailResult(ServiceResultEnum.ORDER_GENERATE_ERROR.getResult());
    }

    @GetMapping("/order/{orderNo}")
    @ApiOperation(value = "订单详情接口", notes = "传参为订单号")
    public Result<WhitesMealOrderDetailVO> orderDetailPage(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToSystemUser SystemUser loginSystemUser){
        return ResultGenerator.genSuccessResult(whitesMealOrderService.getOrderDetailByOrderNoWithUserId(orderNo,loginSystemUser.getUserId()));
    }

    @GetMapping("/order")
    @ApiOperation(value = "订单列表接口", notes = "传参为页码")
    public Result<PageResult<List<WhitesMealOrderListVO>>> orderList(@ApiParam(value = "页码") @RequestParam(required = false) Integer pageNumber,
                                                                     @ApiParam(value = "订单状态:0.待支付 1.待确认 2.待发货 3:已发货 4.交易成功") @RequestParam(required = false) Integer status,
                                                                     @TokenToSystemUser SystemUser loginSystemUser){
        Map params = new HashMap(8);
        if (pageNumber == null || pageNumber < 1){
            pageNumber = 1;
        }
        params.put("userId", loginSystemUser.getUserId());
        params.put("orderStatus", status);
        params.put("page",pageNumber);
        params.put("limit", Constants.ORDER_SEARCH_PAGE_LIMIT);
        // 封装分页请求参数
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(whitesMealOrderService.getOrders(pageUtil));
    }


    @PutMapping("/order/{orderNo}/cancel")
    @ApiOperation(value = "订单取消接口", notes = "传参为订单号")
    public Result cancelOrder(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToSystemUser SystemUser loginSystemUser){
        String cancelOrderResult = whitesMealOrderService.cancelOrder(orderNo, loginSystemUser.getUserId());
        if (ServiceResultEnum.SUCCESS.getResult().equals(cancelOrderResult)){
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(cancelOrderResult);
        }
    }


    @PutMapping("/order/{orderNo}/finish")
    @ApiOperation(value = "确认收货接口", notes = "传参为订单号")
    public Result confirmOrder(@ApiParam(value = "订单号") @PathVariable("orderNo") String orderNo, @TokenToSystemUser SystemUser loginSystemUser){
        String confirmOrderResult = whitesMealOrderService.confirmOrder(orderNo,loginSystemUser.getUserId());
        if (ServiceResultEnum.SUCCESS.getResult().equals(confirmOrderResult)){
            return ResultGenerator.genSuccessResult();
        } else{
            return ResultGenerator.genFailResult(confirmOrderResult);
        }
    }

    @GetMapping("/paySuccess")
    @ApiOperation(value = "模拟支付成功接口", notes ="传参为订单号和支付方式")
    public  Result paySuccessSimulation (@ApiParam(value = "订单号") @RequestParam("orderNo") String orderNo, @ApiParam(value = "支付方式") @RequestParam("payType") int payType){
        String payResult = whitesMealOrderService.paySuccess(orderNo, payType);
        if (ServiceResultEnum.SUCCESS.getResult().equals(payResult)){
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(payResult);
        }
    }

}
